<template>
  <div class="index-classroom">
    <div class="index-classroom-table-box">
      <page-container class="left">

        <el-form inline style="padding-top: 10px; padding-left:20px ;" class="classroom-info">
          <div class="classroom-details">
            <span><span style="font-size: large; color: #32c5ff;">班级名称：</span> <span >{{ classroomDetail.classroomName }}</span> </span>
            <span><span style="font-size: large; color: #32c5ff;">班级类型：</span> <span>{{ classroomDetail.classroomType }}</span></span>
            <span><span style="font-size: large; color: #32c5ff;">开课日期：</span> <span>{{ classroomDetail.startDate }}</span></span>
            <span><span style="font-size: large; color: #32c5ff;">班级状态：</span> <span>{{ getStatusText(classroomDetail.status) }}</span></span>
          </div>
          <div class="classroom-bio" v-html="classroomDetail.bio"></div> <!-- 使用 v-html 展示富文本 -->
        </el-form>

        <div v-if="classroomDetail.classroomId" class="chat-controls">
          <div class="connection-status">
            <span class="status-label">实时消息状态:</span>
            <span class="status-dot" :class="{ 'connected': wsConnected, 'disconnected': !wsConnected }"></span>
            <span>{{ wsConnected ? '已连接' : '未连接' }}</span>
          </div>
          <div class="connection-buttons">
            <el-button 
              :type="wsConnected ? 'warning' : 'primary'" 
              size="default" 
              @click="wsConnected ? disconnectWebSocket() : connectWebSocket()"
              :loading="wsConnecting"
              class="ws-toggle-button"
            >
              <el-icon>
                <component :is="wsConnected ? 'Connection' : 'Link'" />
              </el-icon>
              {{ wsConnected ? '断开实时消息' : '连接实时消息' }}
            </el-button>
            <el-button 
              type="success" 
              size="default" 
              @click="openChat"
              class="chat-open-button"
            >
              <el-icon><ChatDotRound /></el-icon>
              打开班级群聊
            </el-button>
          </div>
        </div>

        <el-form inline="true" ref="formModel" :model="form">
          <el-form-item style="max-width:864px">
            <el-input v-model="params.classroonName" placeholder="课程名称"
              style="width: 100%; margin: 20px 0 20px 10px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="onSearch">搜索</el-button>
            <el-button type="info" plain @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table :data="courseList" height="580px" style="width: 100%">
          <el-table-column align="center" width="100px" label="序号">
            <template #default="{ $index }">
              {{ (params.pageNum - 1) * params.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column align="left" prop="courseName" :show-overflow-tooltip="true" label="课程名称" />
          <el-table-column align="left" prop="teacherName" :show-overflow-tooltip="true" label="教师名称" />
          <el-table-column align="left" prop="videoNum" :show-overflow-tooltip="true" label="视频数量" />
          <el-table-column align="left" prop="createTime" :show-overflow-tooltip="true" label="创建时间" />

          <el-table-column label="操作" align="center" width="180px">
            <template #default="{ row }">
              <el-button type="text" plain @click="goCourseDetail(row.courseId)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
          v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[5, 10, 15, 20]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
          style="margin:20px 100px 20px 0; justify-content: flex-end" />
      </page-container>
      <div class="right">
        <div class="top-box">
          <el-calendar v-model="today"> </el-calendar>
        </div>
      </div>
    </div>
    <ChatDrawer ref="chatDrawerRef" :classroomId="classroomDetail.classroomId" />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue"
import { getMyClassroomDetailService} from "@/apis/classroom";
import { getClassroomCourseListService } from '@/apis/course'
import router from "@/router"
import { ChatDotRound, Connection, Link } from '@element-plus/icons-vue'
import ChatDrawer from '@/components/ChatDrawer.vue'
import { ElMessage } from 'element-plus'
import { 
  initChatWebSocket, 
  disconnectChatWebSocket, 
  getChatConnectionStatus,
  onChatMessage
} from '@/apis/chat'
import websocketService from '@/utils/websocket'

// WebSocket连接状态
const wsConnected = ref(false)
const wsConnecting = ref(false)

// 主动连接WebSocket
const connectWebSocket = async () => {
  // 避免重复连接
  if (wsConnected.value || wsConnecting.value) return
  
  // 设置连接中状态
  wsConnecting.value = true
  
  try {
    // 初始化WebSocket连接
    const success = initChatWebSocket()
    
    if (!success) {
      throw new Error('初始化WebSocket连接失败')
    }
    
    // 设置5秒的连接超时
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('WebSocket连接超时')), 5000)
    })
    
    // 等待连接成功或超时
    await Promise.race([
      new Promise(resolve => {
        // 设置连接状态监听
        websocketService.onConnectionStatusChange = (status) => {
          wsConnected.value = status
          wsConnecting.value = false
          if (status) {
            resolve()
          }
        }
        
        // 注册消息处理
        if (classroomDetail.classroomId) {
          // 注册消息接收处理函数
          onChatMessage(handleNewChatMessage)
        }
      }),
      timeoutPromise
    ])
    
    // 连接成功
    ElMessage.success('实时消息已连接')
  } catch (error) {
    // 连接失败处理
    console.error('WebSocket连接失败:', error)
    wsConnected.value = false
    wsConnecting.value = false
    ElMessage.error(error.message || 'WebSocket连接失败')
  }
}

// 处理新消息
const handleNewChatMessage = (message) => {
  // 判断是否是当前班级的消息
  const targetId = message.data?.groupId;
  if (targetId === classroomDetail.classroomId) {
    // 收到新消息时通知聊天组件刷新
    if (chatDrawerRef.value) {
      chatDrawerRef.value.refreshMessages()
    }
  }
}

// 主动断开WebSocket连接
const disconnectWebSocket = () => {
  // 避免重复断开
  if (!wsConnected.value) return
  
  // 取消消息类型的回调
  websocketService.messageCallbacks.delete('chat_message')
  
  // 断开连接
  const success = disconnectChatWebSocket()
  
  if (success) {
    wsConnected.value = false
    wsConnecting.value = false
    ElMessage.success('已断开实时消息连接')
  } else {
    ElMessage.error('断开实时消息连接失败')
  }
}

// 查询班级详情
// 查询班级全部课程
const classroomDetail = reactive({});
async function getClassroomDetail() {
  const res = await getMyClassroomDetailService();
  if (!res.data) return false;
  Object.assign(classroomDetail, res.data);
  params.classroomId = classroomDetail.classroomId;
  console.log("classroomDetail", classroomDetail);
  return true;
}

onMounted(async () => {
  const detailSuccess = await getClassroomDetail();
  if (!detailSuccess) return;
  await getCourseList();

  // 检查初始连接状态
  const status = getChatConnectionStatus()
  wsConnected.value = status.connected
  wsConnecting.value = status.connecting
  
  // 如果已连接，注册消息处理函数
  if (status.connected && classroomDetail.classroomId) {
    // 设置状态变更回调
    websocketService.onConnectionStatusChange = (status) => {
      wsConnected.value = status
      wsConnecting.value = false
    }
    
    // 注册消息接收处理函数
    onChatMessage(handleNewChatMessage)
  }
});

onUnmounted(() => {
  // 组件卸载时取消WebSocket的事件监听
  websocketService.onConnectionStatusChange = null
  websocketService.messageCallbacks.delete('chat_message')
})

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  courseName: '',
  classroomId: ''
})
let today = ref(new Date()) //日历默认今天
const courseList = ref([]) //题目列表
const total = ref(0)

async function getCourseList() {
  const result = await getClassroomCourseListService(params)
  courseList.value = result.rows
  total.value = result.total
}

// 搜索/重置
function onSearch() {
  params.pageNum = 1
  getCourseList()
}

function onReset() {
  params.pageNum = 1
  params.pageSize = 9
  params.courseName = ''
  getCourseList()
}

// 分页
function handleSizeChange(newSize) {
  params.pageNum = 1
  getCourseList()
}

function handleCurrentChange(newPage) {
  getCourseList()
}

function goCourseDetail(courseId) {
  router.push(`/tims/courseDetails?classroomName=${classroomDetail.classroomName}&courseId=${courseId}`)
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '未发布';
    case 1: return '报名中';
    case 2: return '已开课';
    case 3: return '已结业';
    case 4: return '已下架';
  }
};

const chatDrawerRef = ref(null)

const openChat = () => {
  chatDrawerRef.value?.open()
}
</script>

<style lang="scss" scoped>
.index-classroom-table-box {
  display: flex;
  max-width: 1520px;
  width: 100%;
  justify-content: space-between;

  :deep(.el-pagination) {

    .el-select .el-select__wrapper,
    .el-input .el-input__wrapper {
      height: 24px;
    }
  }

  .left {
    .classroom-info {
        width: 100%;
        height: 50px;
        padding: 20px;
        // box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    
        .classroom-details {
          display: flex;
          justify-content: space-between;
          /* 均匀分布 */
          margin-bottom: 20px;
    
          span {
            flex: 1;
            /* 均分宽度 */
            text-align: center;
            /* 文本居中 */
          }
        }
      }
  }
  .right {
    width: 340px;

    :deep(.top-box) {
      width: 100%;
      height: 345px;
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-radius: 16px;
      background: linear-gradient(164deg, #E2F7FF 0%, #FFFFFF 50%);

      .el-calendar,
      .el-calendar__body {
        background: transparent;
      }

      .el-calendar {
        position: relative;

        .el-calendar__title {
          font-weight: bold;
        }

        .el-calendar__header {
          border: none;
          padding-bottom: 0;
        }

        .el-calendar__button-group {
          text-align: center;
          background: transparent;

          .el-button-group>.el-button {
            color: #1f2122;
            border: none;
            background: rgba(255, 255, 255, .1);
          }
        }

        .el-calendar-table {
          thead th {
            color: #32C5FF;
            font-size: 12px;
            font-weight: bold;
          }

          .el-calendar-day {
            height: 40px;
            text-align: center;
          }

          td {
            border: none;
          }
        }
      }

    }

    .bot-box {
      width: 340px;
      border-radius: 16px;
      padding-top: 0;
      box-sizing: border-box;
      background: #fff;
      position: relative;
      overflow: hidden;

      .title {
        font-weight: bold;
        color: #32C5FF;
        position: relative;
        width: 100%;
        height: 60px;
        padding: 20px;
        padding-bottom: 0;
        background: linear-gradient(169deg, #E2F7FF 0%, #FFFFFF 100%);

        span {
          position: absolute;
          display: flex;
          right: 20px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #32C5FF;
          bottom: 20px;
          cursor: pointer;
        }
      }

      .hot-list {
        width: calc(100% - 40px);
        margin: 0 auto;
        padding-top: 20px;
        padding-bottom: 20px;

        .list-item {
          margin-bottom: 18px;
          cursor: pointer;
          display: flex;
          align-items: center;

          .index-box {
            display: inline-block;
            text-align: center;
            width: 20px;
            font-family: Tensentype-RuiHeiJ, Tensentype-RuiHeiJ;
            font-weight: normal;
            font-size: 18px;
            color: #999999;
            font-weight: bold;
          }

          .txt {
            max-width: calc(100% - 34px);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-left: 10px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: #222222;
            line-height: 22px;
            text-align: left;
            font-style: normal;
          }

          &:hover {
            .txt {
              color: #32C5FF;
            }
          }
        }
      }
    }
  }

  :deep(.left) {
    width: calc(100% - 360px);
    border: none;
    border-radius: 16px;
    overflow: hidden;
    background: linear-gradient(177deg, #f3fcff 0%, #FFFFFF 10%);

    .el-table {
      th.el-table__cell {
        background-color: rgba(50, 197, 255, 0.08) !important;
        font-size: 13px;
      }

      td {
        height: 54px;
      }
    }
    .el-card__header {
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      font-size: 20px;
      color: #222222;
      line-height: 28px;
      text-align: left;
      font-style: normal;
      border: none;
      padding-bottom: 0;
    }
  }
}

.el-input__wrapper {
  background-color: #F8F8F8;
}

.index-classroom {
  background-color: rgba(247, 247, 247, 1);
  display: flex;
  justify-content: center;
  margin-top: 20px;

  .no-border {
    border: none;
  }
}

.el-table {
  th {
    word-break: break-word;
    background-color: #033e7c !important;
    color: #ffff;
    height: 40px;
    font-weight: 700;
    font-size: 14px;
  }
}

.chat-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
  margin: 10px 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-label {
  font-weight: 500;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-dot.connected {
  background-color: #67C23A;
  box-shadow: 0 0 5px #67C23A;
}

.status-dot.disconnected {
  background-color: #F56C6C;
  box-shadow: 0 0 5px #F56C6C;
}

.connection-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chat-open-button,
.ws-toggle-button {
  font-size: 16px;
  padding: 12px 20px;
  height: auto;
  
  .el-icon {
    font-size: 18px;
    margin-right: 6px;
  }
}
</style>

<!-- npm install ace-builds@1.4.13 -->